//
//  BRPayManager.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/9/14.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BRPayManager.h"
#import "BRPayStatusViewController.h"
#define kOrderCheckKey @"kCheckOrderKey"

@interface BRPayManager ()<STPApplePayContextDelegate>

@end

@implementation BRPayManager

+ (BRPayManager *)share
{
    static BRPayManager *man = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        man = [[BRPayManager alloc] init];
    });
    return man;
}

- (void)pre_toConfirmStPay:(NSString *)clientSecret succ:(BRStringBlock)succ fail:(BRStringIntBlock)faile  {

    STPPaymentIntentParams *parm = [[STPPaymentIntentParams alloc] initWithClientSecret:clientSecret];
    [[STPAPIClient sharedClient] confirmPaymentIntentWithParams:parm completion:^(STPPaymentIntent * _Nullable payIntent, NSError * _Nullable error) {
        
        
        if (error) {
            if (faile) {
                faile(error.localizedDescription,error.code);
            }
            [[BRPayManager share] pre_cancle];
        }else {
            if (succ) {
                succ(payIntent.stripeId);
            }
        }
    }];
    
}

/// 主动取消授权 增加容错 不处理响应
- (void)pre_cancle {
    
    [[BRRequestManager shared] GET:@"/api/users/cancel-pre-auth" params:@{} succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
            
        } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
            
        }];
    
}


- (void)checkCard:(STPCardParams *)params isDefault:(BOOL)isDefault succ:(void(^)(BRAddCardModel * addModel))succ faile:(void(^)(void))fail {
    
    
    [[STPAPIClient sharedClient] createTokenWithCard: params completion:^(STPToken * _Nullable token, NSError * _Nullable error) {
        ///判断卡信息是否有误
        if (token == nil || error != nil) {
            
            //错误状态的本地化描述
            NSString *localizedDescription = error.localizedDescription;
            if (BR_StringIsEmpty(localizedDescription)) {
                localizedDescription = Localized(@"Add_Card_Alert_Not_Supported");
                [BRHud showTips:Localized(@"Add_Card_Alert_Not_Supported")];
                
            }else {
                
                [BRHud showTips:[NSString stringWithFormat:@"AT-%@(%ld)",localizedDescription,error.code]];
            }
            if (fail) {
                fail();
            }
            
            return;
        }
        
        
        BRAddCardModel *addModel  = [[BRAddCardModel alloc] init];
        
        NSString *expire = [NSString stringWithFormat:@"%ld/%ld",params.expMonth, params.expYear];///银行卡有效期
        expire = [self changeToExpire:expire];
        addModel.bankExpire = expire;
        
        STPCardBrand cardBrand = [STPCardValidator brandForNumber: params.number];
        
        NSString *bankType = [self br_getCardName:token.card.funding];
        addModel.bankName = [STPCard stringFromBrand:cardBrand];///银行名称
        addModel.bankNo = params.number;///银行卡号后四位
        addModel.bankType = bankType;///卡的类型
        addModel.token = token.tokenId;///银行卡token
        addModel.defaulted = @(isDefault);
        if (params.addressZip.length != 0) {
            addModel.postalCode = params.addressZip;
        }
       
        NSLog(@"获取Stripe 成功");
        if (succ) {
            succ(addModel);
        }
        
    }];
}

- (void)addCard:(BRAddCardModel *)addModel succ:(void(^)(void))succ  faile:(void(^)(void))fail {
    
    NSDictionary *dic = [addModel mj_keyValues];
    
    [[BRRequestManager shared] POST:[BRAPI bankcaerd] params:dic succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        if (succ) {
            succ();
        }
        NSLog(@"添加成功");
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        if (fail) {
            fail();
        }
    }];
}

//转完整年份:11/2021
- (NSString *)changeToExpire:(NSString*)expire
{
    NSArray * array = [expire componentsSeparatedByString:@"/"];
    NSString* mm = array.firstObject;
    if (mm.length != 2) mm =  [NSString stringWithFormat:@"0%@",mm];
    NSString* yy  = array.lastObject;
    if (yy.length != 4) yy =  [NSString stringWithFormat:@"20%@",yy];
    return [NSString stringWithFormat:@"%@/%@",mm,yy];
}

- (void)getPayList:(NSDictionary *)dic succ:(void (^)(NSDictionary * _Nonnull))succ faile:(void (^)(NSInteger))faile {
    
    
    [[BRRequestManager shared] GET:[BRAPI paymentMrthod:dic[@"type"] amount:dic[@"amount"]] params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        NSDictionary *dic = datedic[@"data"];
        if (!BR_DictIsEmpty(dic)) {
           
            succ(dic);
            return;
        }
        faile(1);
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        faile(code);
    }];
    
}

- (NSString *)br_getCardName:(STPCardFundingType)type {
    NSString *bankType = @"";
    switch (type) {
        case STPCardFundingTypeCredit:
            bankType = @"credit";//信用卡
            break;
        case STPCardFundingTypeDebit:
            bankType = @"debit";//借记卡
            break;
        case STPCardFundingTypePrepaid:
            bankType = @"prepaid";
            break;
        case STPCardFundingTypeOther:
            bankType = @"unknown";
            break;
        default:
            break;
    }
    return bankType;
}

#pragma mark - PAY --
- (void)paymentCardWithParams:(NSDictionary *)params succ:(void (^)(NSDictionary * _Nonnull))succ faile:(void (^)(NSInteger, NSString * _Nonnull))fail {
    
    
    [[BRRequestManager shared] POST:[BRAPI pay] params:params succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        if (succ) {
            succ(dataDict);
        }
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        if (fail) {
            fail(code,errMsg);
        }
    }];
}

- (void)checkRefund:(void (^)(NSDictionary * _Nonnull))succ faile:(void (^)(void))fail {
    
    [[BRRequestManager shared] GET:[BRAPI checkRefund] params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        if (succ) {
            succ(dataDict);
        }
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        if (fail) {
            fail();
        }
    }];
}

- (void)refundDeposit:(void (^)(NSDictionary * _Nonnull))succ faile:(void (^)(void))fail {
    
    [[BRRequestManager shared] PUT:[BRAPI refundDeposit] params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        if (succ) {
            succ(dataDict);
        }
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        if (fail) {
            fail();
        }
    }];
}

- (void)paymentAmount:(NSDictionary *)dic succ:(void (^)(NSDictionary * _Nonnull))succ faile:(void (^)(NSInteger))faile {
    
    
    [[BRRequestManager shared] GET:[BRAPI payPriceCalculate] params:dic succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        if (succ) {
            succ(dataDict);
        }
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        if (faile) {
            faile(code);
        }
    }];
    
    
}

#pragma mark - Apple Pay --
- (BOOL)isSupportApplePay {
    return [StripeAPI deviceSupportsApplePay];
}

- (void)applePay:(NSDecimalNumber *)money {
    NSString *merchantIdentifier = STPApplePayKey;
    
    self.country = USERManager.country;
    self.currency = USERManager.currency;
    if (BR_StringIsEmpty(self.currency)) {
        [BRHud hidden];

        [BRUserManager requestConfigs:^{

        } faile:^{

        }];
        // 无配置
        [BRHud showAuto:@"Error Pay config,try again later!"];
        return;
    }
//    self.country = @"US";
//    self.currency = @"USD";
    PKPaymentRequest *paymentRequest = [StripeAPI paymentRequestWithMerchantIdentifier:merchantIdentifier country:self.country currency:self.currency];
    
    NSString *showTitle = [NSString stringWithFormat:@"youdianstar, %@",self.currency];
    // The final line should represent your company;
    // it'll be prepended with the word "Pay" (i.e. "Pay iHats, Inc $50")
    paymentRequest.paymentSummaryItems = @[
        [PKPaymentSummaryItem summaryItemWithLabel:showTitle amount:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%lf",money.floatValue]]]
    ];
    NSLog(@"paymentRequest = %@",paymentRequest);
    // Initialize an STPApplePayContext instance
    STPApplePayContext *applePayContext = [[STPApplePayContext alloc] initWithPaymentRequest:paymentRequest delegate:self];
    if (applePayContext) {
        
        // Present Apple Pay payment sheet
        // 跳转打开系统支付
        [applePayContext presentApplePayWithCompletion:^{
                        
        }];
        
    } else {
        [BRHud hidden];
        // There is a problem with your Apple Pay configuration
        NSLog(@"apple pay 配置错误");
    }
}

- (void)failReturn {
    if (self.paymentStatus) {
        self.paymentStatus(NO);
    }
}

#pragma mark - STPApplePayContextDelegate
- (void)applePayContext:(STPApplePayContext *)context didCreatePaymentMethod:(STPPaymentMethod *)paymentMethod paymentInformation:(PKPayment *)paymentInformation completion:(void (^)(NSString * _Nullable, NSError * _Nullable))completion  {
    
    NSString *clientSecret = self.clientSecret; // Call your backend to create a PaymentIntent (see Server-side step above) and get its client secret
    //    // Call the completion block with the client secret or an error
    
    //paymentMethod.stripeId;
    self.stripeId = paymentMethod.stripeId;
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:self.dic];
    
    if ([self.dic[@"type"] integerValue] == BRPAY_PREAUTI) {
        
//        params[@"type"] = @(BRPAY_PREAUTI);
        
        params[@"paymentMethodId"] = self.stripeId;
        params[@"paymentTokenObject"] = self.stripeId;
        NSString *url = [BRAPI preRent];
        
        NSLog(@"苹果支付参数params==%@",params);
        
        [[BRRequestManager shared] POST:url params:params succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
          
            BRPreRentModel *model = [BRPreRentModel mj_objectWithKeyValues:dataDict[@"data"]];
            
            BROrderDetailModel *dto = [BROrderDetailModel mj_objectWithKeyValues:model.order];

            if (model.resp.status == 11) {
                
                NSLog(@"不需要再次授权");
                [[NSUserDefaults standardUserDefaults] setObject:@"RecentlyusedcardKeyapple" forKey:RecentlyusedcardKey];

                 [[NSUserDefaults standardUserDefaults] synchronize];
                   
                   
                   if (self.applePrePayBlock) {
                       self.applePrePayBlock(dto.orderNo);
                   }
//
                completion(model.resp.displayContent, nil);
                return;
            }

            if (model.resp!=nil) {
                //租借场景:1.预授权租借 2.已授权租借 3.白名单租借
                [BRHud hidden];

                if ([model.resp.displayMode isEqualToString:@"app"]&&model.resp.displayContent.length >0) {
                    // 预授权处理
                    [self pre_toConfirmStPay:model.resp.displayContent succ:^(NSString *stripeId) {
                        

                        
                        NSLog(@"苹果预授权处理成功");
                     
                        [[NSUserDefaults standardUserDefaults] setObject:@"RecentlyusedcardKeyapple" forKey:RecentlyusedcardKey];

                         [[NSUserDefaults standardUserDefaults] synchronize];
                        
                        
                        if (self.applePrePayBlock) {
                            self.applePrePayBlock(dto.orderNo);
                        }
    //
                        completion(model.resp.displayContent, nil);
          
                        
                        
                    } fail:^(NSString *errMsg, NSInteger code) {
    //                    [BRHud hiddenInView:self.view];
                        
                        [BRHud showAuto:[NSString stringWithFormat:@"ST-%@(%ld)",errMsg,code]];
                        NSError *error = [[NSError alloc] initWithDomain:NSURLErrorDomain code:code userInfo:@{NSLocalizedDescriptionKey:errMsg}];
                        completion(model.resp.displayContent, error);
                    }];

                    
                    return;
                }
     
            }

       

    
            
            
        } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
            NSError *error = [[NSError alloc] initWithDomain:NSURLErrorDomain code:code userInfo:@{NSLocalizedDescriptionKey:errMsg}];
            
            completion(clientSecret, error);
            [self payReqFaile:errMsg];
        }];
        
        return;
        
    }
    
   
    params[@"paymentTokenObject"] = paymentMethod.stripeId;
    [[BRPayManager share] paymentCardWithParams:params succ:^(NSDictionary * _Nonnull dic) {
        
        
        BRPaymentModel *model = [BRPaymentModel mj_objectWithKeyValues:dic[@"data"]];
        NSInteger succ = model.success;
//        UIViewController *curVC = [MINUtils findCurrentShowingViewController];
        if (succ == 1) {
            //成功
            [BRHud hidden];
            if (model.payLink.length != 0) {
                // paypal
                
                
                return;
            }
            
            NSLog(@"支付成功");
            completion(model.payResponse.displayContent, nil);

            [self payStatus:BRPAY_SUCC by:model];
            
            return;
            
        }
        if (succ == 3) {
            // 需要校验
            
            
            return;
        }
        if (succ == 2) {
            //失败
            [BRHud hidden];
            NSError *error = [[NSError alloc] initWithDomain:NSURLErrorDomain code:2 userInfo:@{NSLocalizedDescriptionKey:model.failedReason}];
            completion(model.payResponse.displayContent, error);
            

            [self payStatus:BRPAY_FAILED by:model];
            return;
        }
        
    } faile:^(NSInteger code, NSString * _Nonnull errMsg) {
        NSError *error = [[NSError alloc] initWithDomain:NSURLErrorDomain code:code userInfo:@{NSLocalizedDescriptionKey:errMsg}];
        
        completion(clientSecret, error);
    }];

}

- (void)payStatus:(BRPAY_STAUS)status by:(BRPaymentModel *)dto {
    
    if (self.applePayBlock) {
        self.applePayBlock(status, dto);
    }
}

- (void)payReqFaile:(NSString *)errStr {
    
    if (self.applePayReqBlock) {
        self.applePayReqBlock(errStr);
    }
}

- (void)applePayContext:(STPApplePayContext *)context didCompleteWithStatus:(STPPaymentStatus)status error:(NSError *)error {
    
    switch (status) {
        case STPPaymentStatusSuccess:
            // Payment succeeded, show a receipt view
            NSLog(@"支付成功");
//            self.clientSecret;
//            context.apiClient;
            break;

        case STPPaymentStatusError:{
            // Payment failed, show the error
            NSLog(@"apple pay error = %@",error);
            
//            BRPaymentModel *model = [[BRPaymentModel alloc] init];
//            model.failedReason = error.localizedDescription;
//            model.success = 2;
//            if (self.applePayBlock) {
//                self.applePayBlock(BRPAY_FAILED, model);
//            }
            break;
        }
        case STPPaymentStatusUserCancellation:
            // User cancelled the payment
            
            NSLog(@"apple pay 取消了");
            break;
    }
    [BRHud hidden];
}

- (void)applePayContext:(STPApplePayContext *)context didSelectShippingContact:(PKContact *)contact handler:(void (^)(PKPaymentRequestShippingContactUpdate * _Nonnull))handler  API_AVAILABLE(ios(11.0)){
    NSLog(@"didSelectShippingContact");
}

- (void)applePayContext:(STPApplePayContext *)context didSelectShippingMethod:(PKShippingMethod *)shippingMethod handler:(void (^)(PKPaymentRequestShippingMethodUpdate * _Nonnull))handler  API_AVAILABLE(ios(11.0)){
    NSLog(@"didSelectShippingMethod");
}

#pragma mark - Grab Pay --
- (void)grabPay:(NSString *)clientSerce byVC:(UIViewController <STPAuthenticationContext>*)payVC succ:(void(^)(void))succ {
    
    QMUITips *hud = [BRHud show:@"" inView:payVC.view];
    
    NSString *clientSecret = clientSerce; // The client secret of the PaymentIntent created in step 2
    STPPaymentIntentParams *paymentIntentParams = [[STPPaymentIntentParams alloc] initWithClientSecret:clientSecret];
    
    STPPaymentMethodGrabPayParams *grabPayParams = [[STPPaymentMethodGrabPayParams alloc] init];
    paymentIntentParams.paymentMethodParams = [STPPaymentMethodParams paramsWithGrabPay:grabPayParams billingDetails:nil metadata:nil];
    paymentIntentParams.returnURL = @"youdianstar://safepay/";
    [[STPPaymentHandler sharedHandler] confirmPayment:paymentIntentParams
                            withAuthenticationContext:payVC
                                           completion:^(STPPaymentHandlerActionStatus handlerStatus, STPPaymentIntent * handledIntent, NSError * _Nullable handlerError) {
        
        [hud hideAnimated:YES];
        if (handlerError) {
            NSLog(@"handlerError == %@ \n",handlerError);
        }
        
        switch (handlerStatus) {
            case STPPaymentHandlerActionStatusFailed:{
                // Payment failed
                NSLog(@"GrabPay failed");
                
                [BRHud showAuto:@"Pay failed" inView:payVC.view];
                break;
            }
            case STPPaymentHandlerActionStatusCanceled:{
                // Payment canceled
                NSLog(@"GrabPay canceled");
                [BRHud showAuto:@"[BRHud showAuto:@"" inView:payVC.view];" inView:payVC.view];
                break;
            }
            case STPPaymentHandlerActionStatusSucceeded:{
                // Payment succeeded
                [self reportPay:handledIntent.stripeId byVC:payVC succ:succ];
                NSLog(@"GrabPay succ");
                break;
            }
        }
    }];
    
}

- (void)reportPay:(NSString *)stripeId byVC:(UIViewController <STPAuthenticationContext>*)payVC succ:(void(^)(void))succ {
    
//    MBProgressHUD *hud = [MINUtils hudToView: payVC.view withText: Localized(@"MINHud_Request")];
    QMUITips *hud = [BRHud show:@"" inView:payVC.view];
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:1];
    dic[@"paymentIntentId"] = stripeId;
    [[BRRequestManager shared] POST:@"api/walletController/stripePaymentCall" params:dic succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        [hud hideAnimated:YES];
        if (respCode == 0 ) {
            
//            [[UserLoginModelManager shareManager]getUserProfile];
            if (succ) {
                succ();
            }
            
        }else {
            
        }
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [hud hideAnimated: YES];
    }];
}

#pragma mark - Check Oreder --
- (void)save:(NSString *)clientSecret {
    //如果有订单上报失败先缓存
    if (clientSecret.length == 0) return;
    NSString *token = @"1234";
    NSString *orderNo = self.payOrderNo.length != 0 ? self.payOrderNo : @"1233";
    NSDictionary *orderDic = @{@"orderID":orderNo,
                               @"clientSecret":clientSecret,
                               @"brUUID":BRTools.getDeviceUUIDStr,
                               @"token":token
    };
    
    
    NSArray *oldData = @[];
    if ([[BRCacheManager share] hasValueForKey:kOrderCheckKey]) {
        NSData *data = (NSData *)[[BRCacheManager share] getValue:kOrderCheckKey];
        oldData = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    }
    NSMutableArray *orderArr = [NSMutableArray arrayWithArray:oldData];
    [orderArr addObject:orderDic];
    NSData *newData = [NSKeyedArchiver archivedDataWithRootObject:orderArr];
    [[BRCacheManager share] save:newData tableName:kOrderCheckKey];
}

- (BOOL)hasUnpayOreder {
    
    if ([[BRCacheManager share] hasValueForKey:kOrderCheckKey]) {
        NSData *data = (NSData *)[[BRCacheManager share] getValue:kOrderCheckKey];
        NSArray *oldData = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        if (oldData.count > 0) return YES;
    }
    
    return NO;
}

- (NSDictionary *)getOrderDic:(NSString *)clientSecret {
    
    
    if (![[BRCacheManager share] hasValueForKey:kOrderCheckKey]) return @{};
    NSData *data = (NSData *)[[BRCacheManager share] getValue:kOrderCheckKey];
    NSArray *oldData = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    NSMutableArray *orderArr = [NSMutableArray arrayWithArray:oldData];
    for (NSDictionary *dic in orderArr) {
        
        if ([dic[@"clientSecret"] isEqualToString:clientSecret]) {
            return dic;
        }
    }
    if (orderArr.count != 0) return orderArr.firstObject;
    
    return @{};
}

- (void)remove:(NSString *)clientSecret {
    
    NSArray *oldData = @[];
    if ([[BRCacheManager share] hasValueForKey:kOrderCheckKey]) {
        NSData *data = (NSData *)[[BRCacheManager share] getValue:kOrderCheckKey];
        oldData = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    }
    NSMutableArray *orderArr = [NSMutableArray arrayWithArray:oldData];
    for (NSDictionary *dic in orderArr) {
        
        if ([dic[@"clientSecret"] isEqualToString:clientSecret]) {
            [orderArr removeObject:dic];
            break;
        }
    }
    if (orderArr.count == 0) {
        [[BRCacheManager share]  removeObj:kOrderCheckKey];
    }else {
        NSData *newData = [NSKeyedArchiver archivedDataWithRootObject:orderArr];
        [[BRCacheManager share] save:newData tableName:kOrderCheckKey];
    }
}

#pragma mark - amount --
+ (NSString *)br_amount:(NSDecimalNumber *)amount {
    
    
    //    return [BRPayManager br_amount:amount currency:[NSString stringWithFormat:@"%@ ",[BRUserManager share].currency.uppercaseString]];
    
    return [BRPayManager br_amount:amount currency:[BRUserManager share].priceSymbol];
}

+ (NSString *)br_amountFloat:(CGFloat)amountFloat {
    NSDecimalNumber *amount = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%.6f",amountFloat]];
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    [formatter setGroupingSeparator:@","]; // 设置千位分隔符
    [formatter setDecimalSeparator:@"."]; // 设置小数点分隔符
    if ([BRPayManager hasDecimalPart:amount]) {
        formatter.alwaysShowsDecimalSeparator = YES;
        formatter.maximumFractionDigits = 2; // x,xx
        formatter.allowsFloats = YES;
    }
    NSString *formattedAmount = [formatter stringFromNumber:amount];
    return [NSString stringWithFormat:@"%@%@",[BRUserManager share].priceSymbol,formattedAmount];
}

+ (NSString *)br_amount:(NSDecimalNumber *)amount currency:(NSString *)currency {
    
    return [NSString stringWithFormat:@"%@%.2f",currency,amount.floatValue];
    // ↓修改金额格式 1,000.00
    if (amount.floatValue == 0) return [NSString stringWithFormat:@"%@0",currency];
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    [formatter setGroupingSeparator:@","]; // 设置千位分隔符
    [formatter setDecimalSeparator:@"."]; // 设置小数点分隔符

    if ([BRPayManager hasDecimalPart:amount]) {
        formatter.alwaysShowsDecimalSeparator = YES;
        formatter.maximumFractionDigits = 2; // x,xx
        formatter.allowsFloats = YES;
    }
    
    NSString *formattedAmount = [formatter stringFromNumber:amount];
    return [NSString stringWithFormat:@"%@%@",currency,formattedAmount];
    
}

+ (NSString *)br_amount:(NSDecimalNumber *)amount priceSymbol:(NSString *)priceSymbol {
    
    if (![BRPayManager hasDecimalPart:amount]) {
        return [NSString stringWithFormat:@"%@%.0f",priceSymbol,amount.floatValue];
    }
    return [NSString stringWithFormat:@"%@%.2f",priceSymbol,amount.floatValue];
}

+ (BOOL)hasDecimalPart:(NSDecimalNumber *)number {
    NSDecimalNumber *roundedNumber = [number decimalNumberByRoundingAccordingToBehavior:nil];
    return ![number isEqualToNumber:roundedNumber];
}

@end
